package com.bmob.lover.ui.fragment.user

import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.*
import com.bmob.lover.R
import com.bmob.lover.app.ext.toJson
import com.bmob.lover.data.model.enums.BackgroundType
import com.bmob.lover.data.model.bean.Background
import com.bmob.lover.data.model.bean.TheFile
import com.bmob.lover.databinding.FragmentLauncherBgAddBinding
import com.bmob.lover.ui.fragment.base.BaseFileUploadFragment
import com.bmob.lover.viewmodel.base.BaseBmobActionViewModel
import com.bmob.lover.viewmodel.request.LauncherBgSaveViewModel
import com.bmob.lover.viewmodel.state.LauncherBgAddViewModel

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-05-12 10:18
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class UserBgAddFragment private constructor() :
    BaseFileUploadFragment<Background, LauncherBgAddViewModel, FragmentLauncherBgAddBinding>() {

    companion object {
        fun newInstance(type: Int, data: Background? = null): UserBgAddFragment {
            return UserBgAddFragment().apply {
                arguments = Bundle().apply {
                    data?.let {
                        putParcelable(BundleConstant.DATA, it)
                    }
                    putInt(BundleConstant.TYPE, type)
                }
            }
        }
    }

    override fun getTableName(): String  = "UserBackground$mType"

    private val mType: Int by getValueNonNull(BundleConstant.TYPE)
    private val mPublishVm: LauncherBgSaveViewModel by viewModels()
    private val mLauncherBg: Background? by getValue(BundleConstant.DATA)

    override fun getLayoutId(): Int = R.layout.fragment_launcher_bg_add

    override fun getPublishViewModel(): BaseBmobActionViewModel<Background> = mPublishVm

    override fun onPictureNoneSelectClick() {}

    override fun onUploadFileSuccess(files: List<TheFile>) {
        for (file in files) {
            file.mFileName = getViewModel().title.get()
        }
        mLauncherBg.notNull({
            val list = mutableListOf<TheFile>().apply {
                addAll(files)
                addAll(it.getFiles())
            }
            it.attachments = list.toJson()
            mPublishVm.update(it)
        }, {
            mPublishVm.save(mType, files)
        })
    }

    override fun onAddPictureClick() {
        selectImages()
    }

    override fun getTitle(): String = if (mType == BackgroundType.LAUNCHER) "启动页壁纸" else "动态背景"

    override fun getRecyclerView(): RecyclerView = getDataBinding().recyclerView

}